#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021-08-29 9:39 
# @Author : 李中华
# @Email  : 1260429766@qq.com
# @File : loginPage.py
from common.codecTools import urlCodecTool
from common.writeConfig import WriteConfig
from page.basepage import BasePage
from common.readConfig import ReadConfig
from common.readYAML import ReadYAML
from common.logger import Log

yaml = ReadYAML('admin.yaml')
config = ReadConfig()
logger = Log()

logurl = config.getConfValue('mskjWebPlatform', 'logurl') + "/#/login?redirect=%2Fdashboard"


class LoginPage(BasePage):
    def input_username(self):
        username = config.getConfValue('admin登录入口', '用户名')
        self.input_element_text(yaml['用户名'], username)

    def input_password(self):
        password = config.getConfValue('admin登录入口', '密码')
        self.input_element_text(yaml['密码'], password)

    def input_code(self):
        print("请输入验证码")
        code = input()
        self.input_element_text(yaml['验证码'], code)

    def login_click(self):
        self.click(yaml['登录'])

    def logManual(self):
        '''
        当其他地方登录后，cookies变化，此时需要手动登录，获取cookies，并写入到配置文件中，
        如果其他地方没有登录，cookies没有变，先清除cookies，再从配置文件中获取cookies，自动登录
        :return cook，为登录后的cookies:
        '''
        self.getUrl(logurl)
        print('登录前cookie：', self.driver.get_cookies())
        self.input_username()
        self.input_password()
        self.input_code()
        self.login_click()
        cook = self.driver.get_cookies()  # 此时获取到的cook是url编码之后的cookies，不能用，需要url解码
        # print('登录后cookie：', cook)
        cookies = []
        c = {}
        for cookie in cook:
            for key in cookie.keys():
                if isinstance(cookie[key], str):
                    if key == 'name' or key == 'value':  # url解码cook，只需要name和value，其余不需要，登录是用此cookies会自动把其余不全
                        c[key] = urlCodecTool(cookie[key]).urlDecode

            cookies.append(c)
            c = {}
        logger.info('通过手动登录，解析之后的cookies为：' + str(cookies))
        # #cookies写入到配置文件中
        WriteConfig().setConfig('admin登录入口', 'cookies', str(cookies))
        return cookies

    def loginAuto(self):
        """从配置文件中获取cookies，自动登录"""
        cookies = eval(ReadConfig().getConfValue('admin登录入口', 'cookies'))
        self.driver.delete_all_cookies()
        self.getUrl(logurl)
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        print("使用cookies登录后的cookie：", self.driver.get_cookies())
        return self.page_refresh() #返回刷新前和刷新后的url，方便做对比

    def login(self):
        front_current_url,back_current_url = self.loginAuto()
        if front_current_url == back_current_url:
            self.logManual()
        else:
            pass

        # cookies = self.logManual()
        # self.driver.delete_all_cookies()
        # for cookie in cookies:
        #     self.driver.add_cookie(cookie)
        # self.driver.get(logurl)
        # print("骚操作后的cookie：", self.driver.get_cookies())
        # self.page_refresh()


if __name__ == '__main__':
    login = LoginPage()
    # login.getUrl(logurl)
    # print(login.page_title())
    # login.logManual()
    login.login()
